/**
 * 
 */
package com.supcon.plugin;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.ibator.api.Ibator;
import org.apache.ibatis.ibator.config.IbatorConfiguration;
import org.apache.ibatis.ibator.config.xml.IbatorConfigurationParser;
import org.apache.ibatis.ibator.exception.InvalidConfigurationException;
import org.apache.ibatis.ibator.exception.XMLParserException;
import org.apache.ibatis.ibator.internal.DefaultShellCallback;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;

/**
 * @author michael
 * @goal gen
 * @phase compile
 */
public class IBatisGeneratorPlugin extends AbstractMojo {

	/**
	 * The output directory.
	 * 
	 * @parameter expression="src/main/resources/ibatorConfig.xml"
	 */
	String ibatorConfig;

	/**
	 * 
	 * @parameter expression="true"
	 */
	boolean overwirte;

	/**
	 * <i>Maven Internal</i>: Project to interact with.
	 * 
	 * @parameter expression="${project}"
	 * @required
	 * @readonly
	 * @noinspection UnusedDeclaration
	 */
	MavenProject project;

	public String getIbatorConfig() {
		return ibatorConfig;
	}

	public MavenProject getProject() {
		return project;
	}

	public boolean isOverwrite() {
		return overwirte;
	}

	public void execute() throws MojoExecutionException, MojoFailureException {
		// TODO Auto-generated method stub
		getLog().info("ibator starting...");
		File configFile = new File(getProject().getBasedir(), getIbatorConfig());
		List<String> warnings = new ArrayList<String>();
		try {
			IbatorConfigurationParser cp = new IbatorConfigurationParser(warnings,getProject());
			IbatorConfiguration config = cp.parseIbatorConfiguration(configFile);
			DefaultShellCallback callback = new DefaultShellCallback(isOverwrite());
			Ibator ibator = new Ibator(config, callback, warnings);
			ibator.generate(null);
			for (String warning : warnings) {
				getLog().warn(warning);
			}
			getLog().info("ibator ending...");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			getLog().error(e);
		} catch (XMLParserException e) {
			// TODO Auto-generated catch block
			getLog().error(e);
		} catch (InvalidConfigurationException e) {
			// TODO Auto-generated catch block
			getLog().error(e);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			getLog().error(e);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			getLog().error(e);
		}
	}
}
